//
//  WechatPayPlugin.m
//  Runner
//
//  Created by mac on 2020/12/7.
//

#import "WechatPayPlugin.h"
#import <WebKit/WebKit.h>
@interface WechatPayPlugin ()<WKUIDelegate,WKNavigationDelegate>
@property (nonatomic, strong) UIViewController *controller;
@property(nonatomic,strong) WKWebView * webView;

@end

@implementation WechatPayPlugin

static NSString *const CHANNELNAME = @"com.ahj/WechatH5PayPlugin";
static NSString *const METHODNAME  = @"WechatH5Pay";

/**
 *plugin 注册
 */
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:CHANNELNAME binaryMessenger:[registrar messenger]];
    
    UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;

    WechatPayPlugin *plugin = [[WechatPayPlugin alloc]initWithViewController:viewController];
    
    [registrar addMethodCallDelegate:plugin channel:channel];
}

/**
 *flutter端通过通道调用原生方法时会进入以下回调
 */
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    
    if ([call.method isEqualToString:METHODNAME]) {
        
        NSDictionary *dic = call.arguments;
        NSString *mwebUrl = dic[@"mwebUrl"];
        [self goToPay:mwebUrl];
    } else {
        result(FlutterMethodNotImplemented);
    }
}
#pragma mark 支付
- (void)goToPay:(NSString *)mwebUrl {
    _webView = [[WKWebView alloc]initWithFrame:CGRectZero];
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    
    NSMutableURLRequest * request  = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:mwebUrl]];
    [request setValue:@"api.xinanyun.cn//" forHTTPHeaderField:@"Referer"];
    [_webView loadRequest:request];
    [self.controller.view addSubview:_webView];
}

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL *URL = navigationAction.request.URL;
    NSString * urlStr = URL.absoluteString;
    if([urlStr containsString:@"weixin://wap"]) {
        if (![urlStr containsString:@"redirect_url="]) {
            NSString * redirect = @"&redirect_url=api.xinanyun.cn";
            urlStr = [urlStr stringByAppendingString:redirect];
        }
        NSURL * url = [NSURL URLWithString:urlStr];
        NSLog(@"%@",url);
        [[UIApplication sharedApplication] openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (instancetype)initWithViewController:(UIViewController *)viewController {
    self = [super init];
    if (self) {
        self.controller = viewController;
    }
    return self;
}


@end
